package com.zyht.bank.wechat.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.wx.model.dictionary.Constant;
import com.zyht.bank.entity.AxdCertificateInfo;
import com.zyht.bank.entity.AxdCertificateInfoExample;
import com.zyht.bank.entity.AxdCustInfo;
import com.zyht.bank.entity.AxdCustLoan;
import com.zyht.bank.entity.AxdCustLoanExample;
import com.zyht.bank.entity.AxdNoticeTime;
import com.zyht.bank.entity.AxdNoticeTimeExample;
import com.zyht.bank.entity.AxdOrgInfo;
import com.zyht.bank.entity.AxdOrgInfoExample;
import com.zyht.bank.service.AxdCertificateInfoService;
import com.zyht.bank.service.AxdCustLoanService;
import com.zyht.bank.service.AxdNoticeTimeService;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.bank.wechat.intercepter.Binding;
import com.zyht.bank.wechat.vo.AxdCertificateInfoVo;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.wechat.framework.Oauth;
import com.zyht.wechat.framework.constant.ConfigConstants;

/**
 * 凭证上传
 * 
 * @author qjl
 * @data 2017年7月7日
 */
@Controller
@RequestMapping("anon/upload")
public class WechatUpLoadController {
	private String BASEPATH = "/banks/wechat/upload/";
	@Resource
	private AxdCertificateInfoService axdCertificateInfoService;

	@Resource
	private AxdCustLoanService axdCustLoanService;

	@Resource
	private AxdOrgInfoService axdOrgInfoService;

	@Resource
	private AxdNoticeTimeService axdNoticeTimeService;

	/**
	 * 跳转页面
	 * 
	 * @param model
	 * @return
	 */
	@Oauth
	@Binding
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model model, HttpSession session) {
		// 获取绑定信息
		AxdCustInfo custInfo = (AxdCustInfo) session.getAttribute(Constant.CURRENT_USER_BINDINFO_FROM_EVENT_VIEW);
		// 获取客户贷款信息
		AxdCustLoanExample loanExample = new AxdCustLoanExample();
		loanExample.createCriteria().andIsCheckEqualTo("0").andCustNameEqualTo(custInfo.getCustName())
				.andCustIdNumEqualTo(custInfo.getCustIdNum());
		List<AxdCustLoan> custLoans = axdCustLoanService.list(loanExample);

		int num = 0;
		Integer noticeTime = 0;
		if (custLoans.size() > 0) {
			AxdNoticeTimeExample timeExample = new AxdNoticeTimeExample();
			timeExample.createCriteria().andStatusEqualTo("1");
			PageHelper.startPage(1, 1);
			List<AxdNoticeTime> list = axdNoticeTimeService.list(timeExample);
			if (list.size() > 0) {
				AxdNoticeTime axdNoticeTime = list.get(0);
				noticeTime = axdNoticeTime.getNoticeTime();
				noticeTime = noticeTime == null ? 0 : noticeTime;
			}
			for (AxdCustLoan loan : custLoans) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				Date loanDate = loan.getLoanDate();
				if (loanDate != null) {
					int moth = getMoth(sdf.format(loanDate), sdf.format(new Date()));
					if (moth >= noticeTime) {
						num += 1;
					}
				}

			}
			if (num != 0) {

				model.addAttribute("month", noticeTime);
				model.addAttribute("num", num);
			}

			model.addAttribute("custLoans", "1");

		}

		model.addAttribute("bean", custInfo);
		AxdCertificateInfoExample example = new AxdCertificateInfoExample();
		example.createCriteria().andCustIdEqualTo(custInfo.getCustInfoId());
		example.setOrderByClause("create_time ASC");
		List<AxdCertificateInfo> infos = axdCertificateInfoService.list(example);
		// 获取凭证图片
		List<AxdCertificateInfoVo> imgs = axdCertificateInfoService.getImgs(custInfo.getCustInfoId());
		imgs.forEach(img -> {
			if (StringUtils.isNotEmpty(img.getImgUrl())) {
				// 获取缩略图
				String url = PropertiesUtils.getConfig(ConfigConstants.PHONE_FILE_UPLOAD_URL);
				String imgUrl = img.getImgUrl();
				imgUrl = imgUrl.replace("/normal/", "/compress/");
				img.setImgUrl(url + imgUrl);
			}

		});
		if (infos.size() > 0) {
			model.addAttribute("infos", infos);
			model.addAttribute("imgs", imgs);

		}

		model.addAttribute("bean", custInfo);
		return makeView("uploadindex");

	}

	@Oauth
	@Binding
	@RequestMapping(value = "/toedit", method = RequestMethod.GET)
	public String edit(Model model, HttpSession session, Integer id, HttpServletRequest request) {
		AxdCustInfo custInfo = (AxdCustInfo) session.getAttribute(Constant.CURRENT_USER_BINDINFO_FROM_EVENT_VIEW);
		// 获取该客户的贷款信息
		AxdCustLoanExample example = new AxdCustLoanExample();
		example.createCriteria().andCustIdNumEqualTo(custInfo.getCustIdNum()).andCustNameEqualTo(custInfo.getCustName())
				.andCustPhoneEqualTo(custInfo.getCustPhone()).andIsLoanEqualTo("1");
		List<AxdCustLoan> list = axdCustLoanService.list(example);
		if (list.size() == 0) {
			model.addAttribute("loanStatus", "1");
			return makeView("uploadedit");
		}
		// 获取用户上传凭证信息
		AxdCertificateInfoExample certificateInfoExample = new AxdCertificateInfoExample();
		certificateInfoExample.createCriteria().andCustIdEqualTo(custInfo.getCustInfoId());
		certificateInfoExample.setOrderByClause("create_time DESC");
		PageHelper.startPage(1, 1);
		List<AxdCertificateInfo> infos = axdCertificateInfoService.list(certificateInfoExample);
		int num = 0;
		for (AxdCustLoan loan : list) {
			if (loan.getIsCheck().equals("0")) {
				num += 1;
			}
		}

		if (infos.size() > 0 && num == 0) {
			AxdCertificateInfo info = infos.get(0);
			if (info.getExamineStatus().equals("0") || info.getExamineStatus().equals("1")) {
				return "redirect:/anon/upload/index";
			}
		}
		if (id != null) {
			AxdCertificateInfo info = axdCertificateInfoService.findOneById(id);
			if (info != null) {
				for (AxdCustLoan axdCustLoan : list) {
					if (axdCustLoan.getLoanId().equals(info.getCustLoanId())) {
						model.addAttribute("axdCustLoan", axdCustLoan);
					}

				}

			}
		} else {
			if (list.size() > 0) {
				model.addAttribute("loans", list);
			}
		}
		model.addAttribute("bean", custInfo);
		// 获取机构信息axdOrgInfoService
		AxdOrgInfoExample infoExample = new AxdOrgInfoExample();
		if (custInfo.getLoanOrgCode() == null) {
			model.addAttribute("cerId", id);
			return makeView("uploadedit");
		}
		infoExample.createCriteria().andOrgCodeEqualTo(custInfo.getLoanOrgCode());
		PageHelper.startPage(1, 1);
		List<AxdOrgInfo> list2 = axdOrgInfoService.list(infoExample);
		if (list2.size() > 0) {
			model.addAttribute("orgCode", list2.get(0).getOrgCode());
		} else {
			model.addAttribute("orgCode", "1");
		}
		model.addAttribute("cerId", id);

		return makeView("uploadedit");

	}

	@RequestMapping(value = "/imges", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> saveImg(Integer loanId, String[] imgs, HttpSession session) {
		Map<String, String> map = new HashMap<>();
		if (imgs.length == 0) {
			map.put("status", "0");
			map.put("msg", "请选择图片！");
			return map;
		}

		// 获取客户信息
		AxdCustInfo custInfo = (AxdCustInfo) session.getAttribute(Constant.CURRENT_USER_BINDINFO_FROM_EVENT_VIEW);
		// 获取凭证
		AxdCertificateInfoExample example = new AxdCertificateInfoExample();
		example.createCriteria().andCustIdEqualTo(custInfo.getCustInfoId()).andCustLoanIdEqualTo(loanId);
		example.setOrderByClause("create_time DESC");
		PageHelper.startPage(1, 1);
		List<AxdCertificateInfo> list = axdCertificateInfoService.list(example);

		if (list.size() > 0) {
			AxdCertificateInfo axdCertificateInfo = list.get(0);
			if (!axdCertificateInfo.getExamineStatus().equals("2")) {
				map.put("status", "2");
				return map;
			}
		}

		try {
			AxdCertificateInfo info = new AxdCertificateInfo();
			info.setCustId(custInfo.getCustInfoId());
			info.setCreateTime(new Date());
			info.setCustLoanId(loanId);
			info.setExamineStatus("0");
			axdCertificateInfoService.insertInfoAndImg(info, imgs);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "0");
			map.put("msg", "系统内部异常！");
			return map;
		}
		map.put("status", "1");

		return map;

	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> delImgs(String path) {
		Map<String, String> map = new HashMap<String, String>();
		String dir = PropertiesUtils.getConfig(ConfigConstants.PHONE_FILE_UPLOAD_DIR);
		String normal = dir.concat(path);
		path = path.replace("/normal/", "/compress/");
		String compress = dir.concat(path);
		File file = new File(normal);
		File file1 = new File(compress);
		if (file.exists() && file.isFile() && file1.exists() && file1.isFile()) {
			file.delete();
			file1.delete();
			map.put("status", "1");
		} else {
			map.put("status", "0");
		}
		return map;
	}

	private int getMoth(String max, String min) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		try {
			c1.setTime(sdf.parse(max));
			c2.setTime(sdf.parse(min));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
		// 开始日期若小月结束日期
		if (year < 0) {
			year = -year;
			return year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
		}
		return year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);

	}

	private String makeView(String path) {
		return BASEPATH.concat(path);
	}
}
